<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>DeepSeek AI 智能问答助手</h1>
    </div>
    
    <div class="chat-messages" ref="chatMessages">
      <div v-for="message in messages" :key="message.id" 
           :class="['message', message.role === 'user' ? 'user-message' : 'assistant-message']">
        
        <div v-if="message.role === 'assistant' && message.reasoning" class="reasoning-section">
          <div class="reasoning-header">
            <span class="reasoning-icon">🧠</span>
            <span class="reasoning-title">思考过程</span>
          </div>
          <div class="reasoning-content">
            {{ message.reasoning }}
          </div>
        </div>
        
        <div class="message-content">
          {{ message.content }}
        </div>
        
        <div v-if="message.role === 'assistant' && message.usage" class="usage-info">
          Token使用量: 提示词 {{ message.usage.prompt_tokens }}, 完成 {{ message.usage.completion_tokens }}, 总计 {{ message.usage.total_tokens }}
        </div>
      </div>
      
      <div v-if="isTyping" class="message assistant-message typing">
        <div class="message-content">
          <span class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </span>
        </div>
      </div>
    </div>
    
    <div class="chat-input">
      <input 
        v-model="userInput"
        @keyup.enter="sendMessage"
        placeholder="请输入您的问题..."
        :disabled="isTyping"
      />
      <button @click="sendMessage" :disabled="isTyping || !userInput.trim()">
        发送
      </button>
    </div>
  </div>
</template>

<script>
import OpenAI from 'openai';

export default {
  name: 'App',
  data() {
    return {
      messages: [],
      userInput: '',
      isTyping: false,
      client: null
    };
  },
  mounted() {
    try {
      // 初始化OpenAI客户端
      this.client = new OpenAI({
        apiKey: 'sk-317df8b3fe9b4b2a9431f754099c3470',
        baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
        dangerouslyAllowBrowser: true // 允许在浏览器中运行
      });
      console.log('OpenAI客户端初始化成功:', this.client);
    } catch (error) {
      console.error('OpenAI客户端初始化失败:', error);
    }
  },
  methods: {
    async sendMessage() {
      const message = this.userInput.trim();
      if (!message || this.isTyping) return;
      
      // 添加用户消息
      this.messages.push({
        id: Date.now(),
        role: 'user',
        content: message
      });
      
      this.userInput = '';
      this.isTyping = true;
      this.scrollToBottom();
      
      try {
        // 检查客户端是否初始化成功
        if (!this.client || !this.client.chat) {
          throw new Error('OpenAI客户端未正确初始化');
        }
        
        // 准备API调用参数
        const apiMessages = this.messages.map(msg => ({
          role: msg.role, 
          content: msg.content 
        }));
        
        // 创建AI响应消息对象
        const aiMessageId = Date.now() + 1;
        let aiMessage = {
          id: aiMessageId,
          role: 'assistant',
          content: '',
          reasoning: ''
        };
        
        this.messages.push(aiMessage);
        
        console.log('准备调用API:', apiMessages);
        
        // 调用API获取流式响应
        const completion = await this.client.chat.completions.create({
          model: 'deepseek-v3.2-exp',
          messages: apiMessages,
          extra_body: { enable_thinking: true },
          stream: true,
          stream_options: {
            include_usage: true
          }
        });
        
        // 处理流式响应
        for await (const chunk of completion) {
          if (!chunk.choices.length) {
            if (chunk.usage) {
              // 更新Token使用量
              const messageIndex = this.messages.findIndex(m => m.id === aiMessageId);
              if (messageIndex !== -1) {
                // 在Vue 3中，直接修改属性即可保持响应性
                this.messages[messageIndex].usage = chunk.usage;
              }
            }
            continue;
          }
          
          const delta = chunk.choices[0].delta;
          
          // 更新思考内容
          if (delta.reasoning_content) {
            const messageIndex = this.messages.findIndex(m => m.id === aiMessageId);
            if (messageIndex !== -1) {
                // 在Vue 3中，直接修改属性即可保持响应性
                this.messages[messageIndex].reasoning = 
                  (this.messages[messageIndex].reasoning || '') + delta.reasoning_content;
              }
          }
          
          // 更新回复内容
          if (delta.content) {
            const messageIndex = this.messages.findIndex(m => m.id === aiMessageId);
            if (messageIndex !== -1) {
                // 在Vue 3中，直接修改属性即可保持响应性
                this.messages[messageIndex].content = 
                  (this.messages[messageIndex].content || '') + delta.content;
              }
          }
          
          this.scrollToBottom();
        }
        
      } catch (error) {
        console.error('API调用错误:', error);
        this.messages.push({
          id: Date.now() + 2,
          role: 'assistant',
          content: '抱歉，我暂时无法回答您的问题。请稍后再试。\n错误信息: ' + (error.message || '未知错误')
        });
      } finally {
        this.isTyping = false;
        this.scrollToBottom();
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const chatMessages = this.$refs.chatMessages;
        if (chatMessages) {
          chatMessages.scrollTop = chatMessages.scrollHeight;
        }
      });
    }
  }
};
</script>

<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.chat-container {
  max-width: 800px;
  margin: 20px auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.chat-header {
  background: #667eea;
  color: white;
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.chat-header h1 {
  font-size: 24px;
  font-weight: 600;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f8f9fa;
}

.message {
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.user-message {
  display: flex;
  justify-content: flex-end;
}

.assistant-message {
  display: flex;
  justify-content: flex-start;
}

.user-message .message-content {
  background: #667eea;
  color: white;
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px 18px 4px 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.assistant-message .message-content {
  background: white;
  color: #333;
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px 18px 18px 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.reasoning-section {
  background: #f0f4ff;
  border: 1px solid #e0e7ff;
  border-radius: 12px;
  margin-bottom: 12px;
  padding: 12px;
  max-width: 70%;
}

.reasoning-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-weight: 600;
  color: #4f46e5;
}

.reasoning-icon {
  margin-right: 8px;
  font-size: 16px;
}

.reasoning-content {
  color: #374151;
  line-height: 1.5;
  font-size: 14px;
}

.usage-info {
  font-size: 12px;
  color: #6b7280;
  margin-top: 8px;
  padding-left: 16px;
}

.typing {
  opacity: 0.7;
}

.typing-indicator {
  display: inline-block;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  background-color: #667eea;
  border-radius: 50%;
  display: inline-block;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out both;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1.0);
  }
}

.chat-input {
  display: flex;
  padding: 20px;
  background: white;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  gap: 10px;
}

.chat-input input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e2e8f0;
  border-radius: 24px;
  font-size: 16px;
  transition: border-color 0.3s ease;
  outline: none;
}

.chat-input input:focus {
  border-color: #667eea;
}

.chat-input input:disabled {
  background: #f3f4f6;
  cursor: not-allowed;
}

.chat-input button {
  padding: 12px 24px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  outline: none;
}

.chat-input button:hover:not(:disabled) {
  background: #5a67d8;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.chat-input button:active:not(:disabled) {
  transform: translateY(0);
}

.chat-input button:disabled {
  background: #cbd5e0;
  cursor: not-allowed;
  transform: none;
}

@media (max-width: 768px) {
  .chat-container {
    margin: 0;
    height: 100vh;
    border-radius: 0;
  }
  
  .user-message .message-content,
  .assistant-message .message-content,
  .reasoning-section {
    max-width: 85%;
  }
}
</style>